import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Separator } from '@/components/ui/separator';
import { 
  ShoppingCart, 
  Plus, 
  Minus, 
  Trash2, 
  ArrowLeft,
  ShoppingBag
} from 'lucide-react';
import { cartApi } from '@/db/api';
import { useAuth } from 'miaoda-auth-react';
import type { CartItem } from '@/types/types';
import { toast } from 'sonner';

const Cart: React.FC = () => {
  const navigate = useNavigate();
  const { user } = useAuth();
  
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [updating, setUpdating] = useState<string | null>(null);

  useEffect(() => {
    if (!user) {
      navigate('/login');
      return;
    }
    loadCartItems();
  }, [user, navigate]);

  const loadCartItems = async () => {
    try {
      setLoading(true);
      const data = await cartApi.getCartItems();
      setCartItems(data);
      // 默认选中所有商品
      setSelectedItems(data.map(item => item.id));
    } catch (error) {
      console.error('加载购物车失败:', error);
      toast.error('加载购物车失败');
    } finally {
      setLoading(false);
    }
  };

  const updateQuantity = async (itemId: string, newQuantity: number) => {
    if (newQuantity < 1) return;
    
    try {
      setUpdating(itemId);
      await cartApi.updateCartItem(itemId, { quantity: newQuantity });
      setCartItems(prev => 
        prev.map(item => 
          item.id === itemId ? { ...item, quantity: newQuantity } : item
        )
      );
      toast.success('数量已更新');
    } catch (error) {
      console.error('更新数量失败:', error);
      toast.error('更新数量失败');
    } finally {
      setUpdating(null);
    }
  };

  const removeItem = async (itemId: string) => {
    try {
      await cartApi.removeFromCart(itemId);
      setCartItems(prev => prev.filter(item => item.id !== itemId));
      setSelectedItems(prev => prev.filter(id => id !== itemId));
      toast.success('商品已移除');
    } catch (error) {
      console.error('移除商品失败:', error);
      toast.error('移除商品失败');
    }
  };

  const clearCart = async () => {
    try {
      await cartApi.clearCart();
      setCartItems([]);
      setSelectedItems([]);
      toast.success('购物车已清空');
    } catch (error) {
      console.error('清空购物车失败:', error);
      toast.error('清空购物车失败');
    }
  };

  const toggleSelectItem = (itemId: string) => {
    setSelectedItems(prev => 
      prev.includes(itemId)
        ? prev.filter(id => id !== itemId)
        : [...prev, itemId]
    );
  };

  const toggleSelectAll = () => {
    setSelectedItems(prev => 
      prev.length === cartItems.length ? [] : cartItems.map(item => item.id)
    );
  };

  const selectedCartItems = cartItems.filter(item => selectedItems.includes(item.id));
  const totalAmount = selectedCartItems.reduce((sum, item) => {
    return sum + (item.product?.price || 0) * item.quantity;
  }, 0);
  const totalQuantity = selectedCartItems.reduce((sum, item) => sum + item.quantity, 0);

  const handleCheckout = () => {
    if (selectedItems.length === 0) {
      toast.error('请选择要结算的商品');
      return;
    }
    navigate('/checkout', { 
      state: { 
        cartItems: selectedCartItems 
      } 
    });
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-pink-600"></div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Header */}
        <div className="flex items-center gap-4 mb-8">
          <Button variant="ghost" onClick={() => navigate(-1)}>
            <ArrowLeft className="h-5 w-5 mr-2" />
            返回
          </Button>
          <h1 className="text-3xl font-bold text-gray-900">购物车</h1>
          <div className="text-gray-500">
            ({cartItems.length} 件商品)
          </div>
        </div>

        {cartItems.length === 0 ? (
          <div className="text-center py-16">
            <ShoppingBag className="h-24 w-24 text-gray-300 mx-auto mb-6" />
            <h2 className="text-2xl font-semibold text-gray-900 mb-4">购物车是空的</h2>
            <p className="text-gray-600 mb-8">快去挑选你喜欢的商品吧！</p>
            <Button asChild size="lg">
              <Link to="/products">
                <ShoppingCart className="h-5 w-5 mr-2" />
                去购物
              </Link>
            </Button>
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Cart Items */}
            <div className="lg:col-span-2 space-y-4">
              {/* Select All */}
              <Card>
                <CardContent className="p-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id="select-all"
                        checked={selectedItems.length === cartItems.length}
                        onCheckedChange={toggleSelectAll}
                      />
                      <label htmlFor="select-all" className="text-sm font-medium">
                        全选 ({cartItems.length})
                      </label>
                    </div>
                    <Button variant="ghost" size="sm" onClick={clearCart}>
                      <Trash2 className="h-4 w-4 mr-2" />
                      清空购物车
                    </Button>
                  </div>
                </CardContent>
              </Card>

              {/* Cart Items List */}
              {cartItems.map((item) => (
                <Card key={item.id}>
                  <CardContent className="p-6">
                    <div className="flex items-start gap-4">
                      <Checkbox
                        checked={selectedItems.includes(item.id)}
                        onCheckedChange={() => toggleSelectItem(item.id)}
                      />
                      
                      <div className="w-24 h-24 flex-shrink-0 overflow-hidden rounded-lg">
                        <img
                          src={item.product?.images?.[0] || 'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=200'}
                          alt={item.product?.name}
                          className="w-full h-full object-cover"
                        />
                      </div>

                      <div className="flex-1 min-w-0">
                        <Link 
                          to={`/products/${item.product_id}`}
                          className="text-lg font-semibold text-gray-900 hover:text-pink-600 transition-colors"
                        >
                          {item.product?.name}
                        </Link>
                        
                        <div className="mt-1 text-sm text-gray-500 space-y-1">
                          {item.size && <div>尺码: {item.size}</div>}
                          {item.color && <div>颜色: {item.color}</div>}
                          <div>库存: {item.product?.stock}</div>
                        </div>

                        <div className="mt-4 flex items-center justify-between">
                          <div className="flex items-center gap-3">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => updateQuantity(item.id, item.quantity - 1)}
                              disabled={item.quantity <= 1 || updating === item.id}
                            >
                              <Minus className="h-4 w-4" />
                            </Button>
                            <span className="w-12 text-center font-medium">
                              {item.quantity}
                            </span>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => updateQuantity(item.id, item.quantity + 1)}
                              disabled={item.quantity >= (item.product?.stock || 0) || updating === item.id}
                            >
                              <Plus className="h-4 w-4" />
                            </Button>
                          </div>

                          <div className="text-right">
                            <div className="text-lg font-bold text-pink-600">
                              ¥{((item.product?.price || 0) * item.quantity).toFixed(2)}
                            </div>
                            <div className="text-sm text-gray-500">
                              单价: ¥{item.product?.price}
                            </div>
                          </div>
                        </div>
                      </div>

                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => removeItem(item.id)}
                        className="text-red-600 hover:text-red-700 hover:bg-red-50"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>

            {/* Order Summary */}
            <div className="lg:col-span-1">
              <Card className="sticky top-8">
                <CardHeader>
                  <CardTitle>订单摘要</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex justify-between text-sm">
                    <span>已选商品 ({selectedItems.length} 件)</span>
                    <span>{totalQuantity} 件</span>
                  </div>
                  
                  <div className="flex justify-between text-sm">
                    <span>商品总价</span>
                    <span>¥{totalAmount.toFixed(2)}</span>
                  </div>
                  
                  <div className="flex justify-between text-sm">
                    <span>运费</span>
                    <span className="text-green-600">免费</span>
                  </div>
                  
                  <Separator />
                  
                  <div className="flex justify-between text-lg font-bold">
                    <span>合计</span>
                    <span className="text-pink-600">¥{totalAmount.toFixed(2)}</span>
                  </div>
                  
                  <Button 
                    onClick={handleCheckout}
                    disabled={selectedItems.length === 0}
                    className="w-full bg-pink-600 hover:bg-pink-700"
                    size="lg"
                  >
                    去结算 ({selectedItems.length})
                  </Button>
                  
                  <div className="text-xs text-gray-500 text-center">
                    支持微信支付、支付宝等多种支付方式
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Cart;